package m.jclecai.com.activity;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iapppay.sdk.main.IAppPay;
import com.squareup.okhttp.Request;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.base.recyclerview.BaseRecyclerViewAdapter;
import m.jclecai.com.base.recyclerview.BaseViewHolder;
import m.jclecai.com.bean.OrderDetailBean;
import m.jclecai.com.bean.PayChannelBean;
import m.jclecai.com.bean.RecordsBean;
import m.jclecai.com.bean.ResponsePayWayList;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.dialog.WaitPayOrderDialog;
import m.jclecai.com.listener.Callback;
import m.jclecai.com.pay.AiBeiPayImpl;
import m.jclecai.com.pay.BasePayImpl;
import m.jclecai.com.pay.PayWithQrCodePayImpl;
import m.jclecai.com.pay.QiFenQianPayImpl;
import m.jclecai.com.pay.RedirectPayImpl;
import m.jclecai.com.pay.RequestPayImpl;
import m.jclecai.com.pay.WebPayPayImpl;
import m.jclecai.com.pay.WeiFuTongPayImpl;
import m.jclecai.com.service.DownloadService;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.ChannelUtil;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.ScreenUtil;
import m.jclecai.com.utils.ToastUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import rx.Subscription;
import rx.functions.Action1;

public class RechargeActivity extends BaseActivity {

    @BindView(R.id.et_amount_money)
    EditText mEtAmountMoney;

    @BindView(R.id.rb_20)
    CheckBox mRb20;

    @BindView(R.id.rb_100)
    CheckBox mRb100;

    @BindView(R.id.rb_500)
    CheckBox mRb500;

    @BindView(R.id.rb_1000)
    CheckBox mRb1000;

    @BindView(R.id.rv_pay_channel)
    RecyclerView mRvPayChannel;

    @BindView(R.id.tv_kefu_number)
    TextView mTvKefuNumber;


    @BindView(R.id.rg_group)
    LinearLayout rgGroup;

    int chargeStatus = RESULT_CANCELED;

    int mPayMoney = 100;

    //订单的一些相关信息；
    UserBean userBean;
    private PayChannelAdapter mPayChannelAdapter;
    private ArrayList<CheckBox> mCbBoxs = new ArrayList<>();
    private PayChannelBean mCurCheckedBean;
    private Subscription mQueryResultSubscribe;
    String userName;
    String password;


    @Override
    protected int getContentView() {
        return R.layout.activity_recharge_;
    }


    @Override
    public void initData() {
        userName = PreferenceUtil.getUserName(this);
        password = PreferenceUtil.getPassword(this);
        mEtAmountMoney.setText(String.valueOf(mPayMoney));
        userBean = PreferenceUtil.readUser(this);
        //爱贝的初始化操作
        IAppPay.init(this, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, "3015703585");
        showDialog();
        initPayChannel();
        //初始化客服的电话；
//        mTvKefuNumber.setText("客服电话: " + PreferenceUtil.readString(this, PreferenceUtil.KF_NUMBER, ""));

        mCbBoxs.add(mRb20);
        mCbBoxs.add(mRb100);
        mCbBoxs.add(mRb500);
        mCbBoxs.add(mRb1000);
        setCheck(mRb20);
        getDefAmoutBottom();
    }

    /**
     * 动态获取默认金额按钮
     */
    private void getDefAmoutBottom() {
        HttpManager.getAsyn("chargeMoney.php?user=" + userName + "&password=" + password, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                DisPlay("请检查网络！！！");
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                JSONArray obj = FastOk.get(response, JSONArray.class);
                if (obj != null) {
                    //填充按钮 搜先隐藏原来的金额按钮
                    int childCount = rgGroup.getChildCount();
                    for (int i = 0; i < childCount; i++) {
                        rgGroup.getChildAt(i).setVisibility(View.GONE);
                    }
                    //加入新的金额按钮
                    for (int i = 0; i < obj.size(); i++) {
                        JSONObject jsonObject = obj.getJSONObject(i);
                        String amount = jsonObject.getString("amount");
                        String addmoney = jsonObject.getString("addmoney");
                        StringBuffer sb = new StringBuffer();
                        sb.append("<small>" + amount);
                        sb.append("元</small>");
                        if (!"0".equals(addmoney)) {
                            sb.append("<br><small><small>赠送");
                            sb.append(addmoney);
                            sb.append("元</small></small>");
                        }

                        CheckBox cb = new CheckBox(RechargeActivity.this);
                        cb.setBackgroundResource(R.drawable.charge_check_bg);
                        cb.setButtonDrawable(null);
                        cb.setGravity(Gravity.CENTER);
                        cb.setTag(amount);
                        cb.setText(Html.fromHtml(sb.toString()));
                        cb.setTextColor(ContextCompat.getColorStateList(RechargeActivity.this, R.color.selector_black_red));
                        cb.setId(1000000 + i);
                        cb.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                setCheck(v);
                                mPayMoney = Integer.valueOf(v.getTag().toString());
                                mEtAmountMoney.setText(String.valueOf(mPayMoney));
                                mEtAmountMoney.setSelection(String.valueOf(mPayMoney).length());
                            }
                        });
                        mCbBoxs.add(cb);
                        rgGroup.addView(cb);
                        LinearLayout.LayoutParams layoutParams =
                                (LinearLayout.LayoutParams) cb.getLayoutParams();
                        layoutParams.weight = 1;
                        layoutParams.width = 0;
                        layoutParams.height = RecyclerView.LayoutParams.MATCH_PARENT;
                        if (i > 0){
                            layoutParams.leftMargin = ScreenUtil.dip2px(RechargeActivity.this, 5);
                        }else{
                            setCheck(cb);
                            mPayMoney = Integer.valueOf(cb.getText().toString().replace("元",""));
                            mEtAmountMoney.setText(String.valueOf(mPayMoney));
                            mEtAmountMoney.setSelection(String.valueOf(mPayMoney).length());
                        }
                    }
                }
            }
        });
    }


    ResponsePayWayList payWayList = null;
    /**
     * 初始化支付的渠道；
     */
    private void initPayChannel() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(RechargeActivity.this);
        final View view = View.inflate(RechargeActivity.this, R.layout.dialog_update_layout, null);
        builder.setView(view);
        //这里我们请求网络来决定有几种充值方式
        final List<PayChannelBean> payWays = new ArrayList<PayChannelBean>();

        HttpManager.getAsyn(Constant_Url.PAY_WAY + "&appstore=" + ChannelUtil.getChannel(), new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                DisPlay("请检查网络！！！");
                payWays.add(createWeChatNumberPay());
                if (mPayChannelAdapter != null)
                    mPayChannelAdapter.refresh(payWays);
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                if (!TextUtils.isEmpty(response)) {
                    payWayList = FastOk.get(response, ResponsePayWayList.class);
                    payWays.addAll(filterResPayWayList(payWayList));
                    if(!TextUtils.isEmpty(payWayList.getDownload())){
                        try {
                            final AlertDialog alertDialog = builder.create();

                            RxPermissions rxPermissions = new RxPermissions(RechargeActivity.this);
                            rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                    .subscribe(new Action1<Boolean>() {
                                        @Override
                                        public void call(Boolean aBoolean) {
                                            if (aBoolean) {
                                                alertDialog.show();
                                            } else {
                                                DisPlay("获取权限失败！！！");
                                            }
                                        }
                                    });


                            view.findViewById(R.id.tv_update).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    //这里我们要做的一个操作就是升级；
                                    Intent intent = new Intent(RechargeActivity.this, DownloadService.class);
                                    intent.putExtra(DownloadService.APK_SIZE, "");
                                    intent.putExtra(DownloadService.DOWNLOAD_URL, payWayList.getDownload());
                                    RechargeActivity.this.startService(intent);
                                    alertDialog.dismiss();
                                }
                            });
                            //这里表示需要更新；在这里写的话可以偷懒
                            view.findViewById(R.id.tv_no_update).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    alertDialog.dismiss();
                                }
                            });
                            String content = payWayList.getMessage();
                            ((TextView) view.findViewById(R.id.tv_content)).setText(content);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                } else {
                    DisPlay("服务器异常，稍后重试！！");
                    payWays.add(createWeChatNumberPay());
                }
                //刷新数据；
                if (mPayChannelAdapter != null) mPayChannelAdapter.refresh(payWays);
            }
        });
    }

    //在拦截订单前先看看是否绑定了银行卡和身份证
    private void checkBindInfo(final Callback callback) {
        HashMap<String, String> pair = new HashMap<>();
        pair.put("user", userName);
        pair.put("password", password);
        final Intent[] intent = {null};
        HttpManager.postAsyn(Constant_Url.GET_USER_INFO, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay("请检查网络！！！");
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                UserBean usb = FastOk.get(response, UserBean.class);
                if (usb == null) {
                    DisPlay("服务器异常！！！");
                } else {
                    if ("0".equals(usb.getStatus())) {
                        String alertTitle = "";
                        if (TextUtils.isEmpty(usb.getBankno())) {
                            alertTitle = "充值前先绑定真实身份证，确保账户安全";
                            intent[0] = new Intent(RechargeActivity.this, BindbankCardActivity.class);
                        } else if (TextUtils.isEmpty(usb.getIdcard())) {
                            alertTitle = "充值前先绑定银行卡，确保账户安全";
                            intent[0] = new Intent(RechargeActivity.this, BindIDCardActivity.class);
                        } else {
                            if (callback != null) callback.callback();
                        }
                        if (intent[0] != null) {
                            showAlertDialog("温馨提示", alertTitle, "知道了", "前往", null,
                                    new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            startActivity(intent[0]);
                                        }
                                    });
                        }
                    } else {
                        DisPlay(usb.getMessage());
                    }
                }
            }
        }, pair);
    }

    //充值前拦截下 看是否有未完成订单
    private void interceptCharge(final Callback callback) {
        if (mPayChannelAdapter.getCheckedBean()==null)
            return;
        //这里我们请求网络来决定有几种充值方式
        final List<PayChannelBean> payWays = new ArrayList<PayChannelBean>();
        StringBuffer url = new StringBuffer(Constant_Url.I_CHARGE);
        url.append("channel=" + mPayChannelAdapter.getCheckedBean().getChannel() + "&");
        url.append("appstore=" + ChannelUtil.getChannel() + "&");
        url.append("money=" + mPayMoney + "&");
        url.append("user=" + userName + "&");
        url.append("password=" + password);
        HttpManager.getAsyn(url.toString(), new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                DisPlay("请检查网络！！！");
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                if (!TextUtils.isEmpty(response)) {
                    OrderDetailBean payWayList = FastOk.get(response, OrderDetailBean.class);
                    List<RecordsBean> records = payWayList.getRecords();
                    if (records == null) {
                        if (TextUtils.isEmpty(payWayList.getProjectno())) {
                            //多次频繁操作
                            //{"message":"操作过于频繁,两次充值间隔最少1分钟","status":"1007"}
                            ToastUtil.showToast(RechargeActivity.this, payWayList.getMessage());
                        } else {
                            //如果有 projectno 表示刚生成的新订单 直接开始支付
                            //ex:{"message":"订单号生成成功","money":"20","projectno":"C2018031016341514119","status":"0","ipaddr":"220.249.92.34"}
                            if (callback != null) callback.payOrder(payWayList);
                        }
                    } else {
                        //如果有 records 表示已存在有很多订单
                        //{"message":"您有以下未完成订单号列表","money":"20","status":"1000","projectno":"","ipaddr":"220.249.92.34","records":[{"user_id":"3422","amount":"20.00","projectno":"C2018031015593481820","addtime":"2018-03-10 15:59:34"}]}
                        if (callback != null) callback.waitPayOrder(records);
                    }
                }
            }
        });
    }

    /**
     * 对服务器返回的支付渠道进行过滤，没有打开的就不现实；
     *
     * @param payWayList
     */
    private List<PayChannelBean> filterResPayWayList(ResponsePayWayList payWayList) {
        ArrayList<PayChannelBean> payWays = new ArrayList<>();
        if (payWayList.getStatus().equals("0")) {
            //这里我们将现已经开放的充值接口放到adapter中；
            PayChannelBean payChannelBean = createWeChatNumberPay();
            payWayList.getRecords().add(0,payChannelBean);
            boolean hasQifenQian = false;
            for (int i = 0; i < payWayList.getRecords().size(); i++) {
                PayChannelBean channelBean = payWayList.getRecords().get(i);
                //过滤没有打开的支付渠道
                if (!channelBean.isClose()) {
                    payWays.add(channelBean);
                    //设置一个默认值；
                    if (i == 0) {
                        channelBean.setChecked(true);
                    }
                  /*  if("6".equals(channelBean.getSystemID()) && !hasQifenQian) {
                        //这里表示有七分钱，而且是第一次进来，我们其进行一个设置添加一个原生的支付渠道；
                        PayChannelBean qiFenQianNative = new PayChannelBean();
                        qiFenQianNative.setLogo("sevenPay");
                        qiFenQianNative.setSystemID("6");
                        qiFenQianNative.setName("支付宝");
                        payWays.add(qiFenQianNative);
                        hasQifenQian=true;
                        setRealPayMethod(qiFenQianNative);
                    }*/
                    setRealPayMethod(channelBean);
                }
            }
        } else {
            DisPlay(payWayList.getMessage());
            payWays.add(createWeChatNumberPay());
        }
        return payWays;
    }

    /**
     * 根据对应的支付渠道设置对应的Ipay
     * 支付划分为四类 包含
     * 扫码(qrcode)
     * 网页跳转(redirect)
     * 原生支付(native)
     * 其他(--)
     *
     * @param channel
     */
    private void setRealPayMethod(PayChannelBean channel) {

        String channelStr = channel.getChannel();
        channelStr = TextUtils.isEmpty(channelStr) ? "none" : channelStr;
        if (channelStr.contains("qrcode")) {
//            "[ANDROID]qrcode.qqpay"://QQ钱包扫码
//            "[ANDROID]qrcode.alipay"://支付宝扫码
//            "[ANDROID]qrcode.wxpay"://微信扫码
            //扫码
            channel.setIPay(new PayWithQrCodePayImpl(this, userBean.getUser_id()));
        } else if (channelStr.contains("redirect")) {
//            "[ANDROID]alipay.ys.redirect"://银盛 支付宝
//            "[ANDROID]sumpay.alipay.redirect"://统统付
//            "[ANDROID]alipay.h5.redirect"://支付宝(WAP)
            channel.setIPay(new RedirectPayImpl(this));
        } else if (channelStr.contains("native")) {
            if (!channelStr.contains("iapppay")) {
//            "[ANDROID]tenpay.wappay.native"://QQ钱包
//            "[ANDROID]pay.alipay.native"://支付宝(APP)
                channel.setIPay(new WeiFuTongPayImpl(this, userName, password));
            } else {
                //这里表示爱贝的支付方式；
                //"[ANDROID]iapppay.native"
                channel.setIPay(new AiBeiPayImpl(this, userBean.getUser_id()));
            }
        } else {
            channel.setIPay(new RequestPayImpl(this));
        }
        /**
         switch (channelStr) {
         case "[ANDROID]qrcode.qqpay"://QQ钱包扫码
         case "[ANDROID]qrcode.alipay"://支付宝扫码
         case "[ANDROID]qrcode.wxpay"://微信扫码
         //扫码
         channel.setIPay(new PayWithQrCodePayImpl(this, userBean.getUser_id()));
         break;
         case "[ANDROID]alipay.ys.redirect"://银盛 支付宝
         case "[ANDROID]sumpay.alipay.redirect"://统统付
         case "[ANDROID]alipay.h5.redirect"://支付宝(WAP)
         //网页的充值方式；
         //                channel.setIPay(new WebPayPayImpl(this, userName, password));
         channel.setIPay(new RedirectPayImpl(this));
         break;
         case "[ANDROID]weixin.qfq"://微信(官方)
         case "[ANDROID]alipay.qfq"://支付宝(官方)
         channel.setIPay(new QiFenQianPayImpl(this, userName, password));
         break;
         //            case "[ANDROID]tenpay.wappay.native"://QQ钱包
         //                channel.setIPay(new RequestPayImpl(this));
         //                break;
         case "[ANDROID]tenpay.wappay.native"://QQ钱包
         case "[ANDROID]pay.alipay.native"://支付宝(APP)
         channel.setIPay(new WeiFuTongPayImpl(this,userName,password));
         break;
         case "[ANDROID]iapppay.native"://爱贝聚合支付
         //这里表示爱贝的支付方式；
         channel.setIPay(new AiBeiPayImpl(this, userBean.getUser_id()));
         break;
         }
         **/
//        if ("0".equals(channel.getSystemID())) {
//            //网页的充值方式；
//            channel.setIPay(new WebPayPayImpl(this, userName, password));
//        } else if ("1".equals(channel.getSystemID())) {
//            //威富通的充值方式；
//            channel.setIPay(new WeiFuTongPayImpl(this, userName, password));
//        } else if ("3".equals(channel.getSystemID())) {
//            //扫码
//            channel.setIPay(new PayWithQrCodePayImpl(this, userBean.getUser_id()));
//        } else if ("4".equals(channel.getSystemID())) {
//            //这里表示爱贝的支付方式；
//            channel.setIPay(new AiBeiPayImpl(this, userBean.getUser_id()));
//        } else if ("6".equals(channel.getSystemID())) {
//            channel.setIPay(new QiFenQianPayImpl(this, userName, password));
//        }
    }

    /**
     * @return
     */
    private PayChannelBean createWeChatNumberPay() {
        PayChannelBean payChannelBean = new PayChannelBean();
        payChannelBean.setTitle("添加官方微信好友,备注用户名快捷转账");
        payChannelBean.setName("微信添加好友转账");
        payChannelBean.setIcon(R.drawable.wxicon_1);
        payChannelBean.setIsclose(0);
        payChannelBean.setSystemID("native");
        return payChannelBean;
    }

    @Override
    public void initView() {
        setTitle("充值");
        leftOptionText("");
//        rightOptionText("客服");
        mRvPayChannel.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mPayChannelAdapter = new PayChannelAdapter(null);
        mRvPayChannel.setAdapter(mPayChannelAdapter);
        //设置光标的初始位置；
        mEtAmountMoney.setSelection(mEtAmountMoney.getText().toString().length());
    }

    private void setCheck(View v) {
        for (CheckBox cbBox : mCbBoxs) {
            Log.e("CID", cbBox.getId() + "-" + v.getId());
            if (cbBox.getId() == v.getId()) {
                cbBox.setChecked(true);
            } else {
                cbBox.setChecked(false);
            }
        }
    }


    @OnClick({R.id.rb_20, R.id.rb_100, R.id.rb_500, R.id.rb_1000})
    public void payMoney(View view) {
        mPayMoney = Integer.valueOf(view.getTag().toString());
        mEtAmountMoney.setText(String.valueOf(mPayMoney));
        mEtAmountMoney.setSelection(String.valueOf(mPayMoney).length());
    }


    @OnTextChanged(R.id.et_amount_money)
    void afterTextChanged(Editable s) {
        if (TextUtils.isEmpty(s.toString()))
            mPayMoney = 0;
        else
            mPayMoney = Integer.valueOf(s.toString());

        if (mCbBoxs != null) {
            for (CheckBox cbBox : mCbBoxs) {
                String tag = cbBox.getTag().toString();
                float parseInt = Float.parseFloat(tag);
                if (parseInt == mPayMoney && cbBox.getVisibility() == View.VISIBLE) {
                    setCheck(cbBox);
                    return;
                }
            }
        }
        //如果没有选中的状态，则清空所有的状态
        if (mCbBoxs != null) {
            for (CheckBox cbBox : mCbBoxs) {
                cbBox.setChecked(false);
            }
        }
    }


    @OnClick(R.id.tv_sure)
    public void pay(View view) {
        if (TextUtils.isEmpty(mEtAmountMoney.getText().toString())) {
            DisPlay("请输入要充值的金额");
            return;
        }

        mCurCheckedBean = mPayChannelAdapter.getCheckedBean();
        if (mCurCheckedBean==null)
            return;
        if (mCurCheckedBean.getIPay() == null) {
            ToastUtil.showToast(this, "支付通道正在升级维护");
            return;
        }
//        showDialog();
        //扫码不拦截
        if (mCurCheckedBean!=null){
            if (!TextUtils.isEmpty(mCurCheckedBean.getChannel())){
                if (mCurCheckedBean.getChannel().contains("qrcode")) {
                    mCurCheckedBean.getIPay().pay(mCurCheckedBean, mPayMoney + "");
                    return;
                }
            }
        }


        /**
         * 模拟支付测试
         */
//        OrderDetailBean payWayList = new OrderDetailBean();
//        payWayList.setIpaddr("220.249.92.34");
//        payWayList.setMoney(500);
//        payWayList.setProjectno("C2018053110120130659");
//        mCurCheckedBean.setProjectno(payWayList.getProjectno());
//        mCurCheckedBean.setAmount(500);
//        mCurCheckedBean.setIpaddr(payWayList.getIpaddr());
//        mCurCheckedBean.getIPay().pay(mCurCheckedBean, String.valueOf(payWayList.getMoney()));


//        checkBindInfo(new Callback() {
//            @Override
//            public void callback() {
//                super.callback();
        interceptCharge(new Callback<List<RecordsBean>>() {
            @Override
            public void waitPayOrder(List<RecordsBean> records) {
                super.waitPayOrder(records);
                //如果有訂單显示弹窗 支付现有订单
                WaitPayOrderDialog dialog = new WaitPayOrderDialog(RechargeActivity.this);
                dialog.setData(records);
                dialog.show();
                dialog.setCallback(new Callback() {
                    @Override
                    public void callback(Object o) {
                        super.callback(o);
                        RecordsBean bean = (RecordsBean) o;
                        double type = Math.floor(Math.random() * 3 + 1);
                        String url = Constant_Url.CP_PAY + "?price=" + bean.getAmount() + "&pay_id=" + userBean.getUser_id() + "&type=" + type + "&channel=[ANDROID]qrcode.random&appstore=" + ChannelUtil.getChannel();
                        ((BasePayImpl) mCurCheckedBean.getIPay()).weakUpPay(url);
                        //跳到二维码支付
//                        mCurCheckedBean.setProjectno(bean.getProjectno());
//                        mCurCheckedBean.getIPay().pay(mCurCheckedBean, String.valueOf(bean.getAmount()));
                    }
                });
            }

            @Override
            public void payOrder(OrderDetailBean payWayList) {//没用有效订单直接提交
                super.payOrder(payWayList);
                mCurCheckedBean.setProjectno(payWayList.getProjectno());
                mCurCheckedBean.setAmount(mPayMoney);
                mCurCheckedBean.setIpaddr(payWayList.getIpaddr());
                mCurCheckedBean.getIPay().pay(mCurCheckedBean, String.valueOf(payWayList.getMoney()));
            }
        });
//            }
//        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (data == null) {
            DisPlay("未知错误");
            return;
        }
        dissDialog();
        String respCode = data.getExtras().getString("resultCode");
        if (!TextUtils.isEmpty(respCode) && respCode.equalsIgnoreCase("success")) {
            chargeStatus = RESULT_OK;
            //标示支付成功
            DisPlay("支付成功");
        } else { //其他状态NOPAY状态：取消支付，未支付等状态
            chargeStatus = RESULT_CANCELED;
            DisPlay("未支付");
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    protected void close() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        setResult(chargeStatus);
        finish();
    }

    //==============充值的adapter====================

    public class PayChannelAdapter extends BaseRecyclerViewAdapter<PayChannelBean> {

        public int mCheckedPosition;

        public PayChannelAdapter(List<PayChannelBean> DList) {
            super(DList);
        }

        @Override
        public int getItemView() {
            return R.layout.item_pay_channel;
        }

        @Override
        protected void bindViewHolder(BaseViewHolder holder, final PayChannelBean bean, final int position) {

            holder.getImageView(R.id.iv_pay_channel_icon).setImageResource(bean.getIcon());

            holder.getTextView(R.id.tv_pay_channel_name).setText(bean.getName());

            holder.getTextView(R.id.tv_pay_channel_dec).setText(bean.getTitle());

            ((RadioButton) holder.getView(R.id.rb_pay_channel_check)).setChecked(bean.isChecked());

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if ("native".equals(bean.getSystemID())) {

                        startActivity(
                                new Intent(RechargeActivity.this,
                                        WechatDetailActivity.class));
                        //公众号充值方式；
//                        getWechatApi();
//                        DisPlay("已复制到剪切板");
//                        BaseUtils.setClipString(RechargeActivity.this, "武汉大彩神");
//                        BaseUtils.startWeChat(RechargeActivity.this);
                        return;
                    }

                    getDataList().get(mCheckedPosition).setChecked(false);
                    mCheckedPosition = position;
                    getDataList().get(position).setChecked(true);
                    notifyDataSetChanged();
                }
            });
            holder.getView(R.id.rb_pay_channel_check).setVisibility(View.VISIBLE);
            //微信公众号充值是没有SystemID的,显示充值按钮；
            if ("native".equals(bean.getSystemID())) {
                holder.getView(R.id.rb_pay_channel_check).setVisibility(View.INVISIBLE);
            }

            //这里是线的操作；
            holder.getView(R.id.view_line).setVisibility(View.VISIBLE);
            //不显示最后一面线
            if (position == getItemCount() - 1) {
                holder.getView(R.id.view_line).setVisibility(View.INVISIBLE);
            }
        }

        public int getCheckedPosition() {
            return mCheckedPosition;
        }

        public PayChannelBean getCheckedBean() {
            PayChannelBean payChannelBean = null;
            if (null!=mDList&&mDList.size()>0){
                payChannelBean = mDList.get(mCheckedPosition);
            }
            return payChannelBean;
        }
    }



    /**
     * 跳转到微信
     */
    private void getWechatApi(){
        try {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            ComponentName cmp = new ComponentName("com.tencent.mm","com.tencent.mm.ui.LauncherUI");
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(cmp);
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            // TODO: handle exception
            ToastUtil.showToast(RechargeActivity.this,"检查到您手机没有安装微信，请安装后使用该功能");
        }
    }


}
